package com.ykt.controller;

import com.jfinal.aop.Before;
import com.ykt.common.constant.ParamNames;
import com.ykt.common.utils.Colls;
import com.ykt.common.utils.UB;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.converter.GoodsCategoryConverter;
import com.ykt.converter.GoodsConverter;
import com.ykt.converter.MediaSourceConverter;
import com.ykt.model.Goods;
import com.ykt.model.GoodsCategory;
import com.ykt.model.MediaSource;
import com.ykt.model.Shop;
import com.ykt.service.GoodsCategoryService;
import com.ykt.service.GoodsService;
import com.ykt.service.MediaSourceService;
import com.ykt.service.ShopService;
import com.ykt.validator.CommonValidator;
import com.ykt.vo.GoodsCategoryVo;
import com.ykt.vo.GoodsVo;
import com.ykt.vo.MediaSourceVo;
import com.ykt.vo.ResultVo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品操作
 *
 * @author wing
 * @version 1.0.0
 */
public class GoodsController extends BaseController {


    private ShopService shopService = enhance(ShopService.class.getName(), ShopService.class);
    private GoodsService goodsService = enhance(GoodsService.class.getName(), GoodsService.class);
    private GoodsCategoryService categoryService = enhance(GoodsCategoryService.class.getName(), GoodsCategoryService.class);
    private MediaSourceService mediaSourceService = enhance(MediaSourceService.class.getName(), MediaSourceService.class);


    /**
     * 查询市场的商品最新价格
     */
    @Before(CommonValidator.MarketIdValidator.class)
    public void newPrice() {
        int userId = UB.i(getPara("userId"));
        int marketId = getParaToInt("marketId", -1);

        PageParam<Integer> param = super.toPageParam(marketId);
        PageData<Goods> pd = goodsService.findGoodsByUpdateTime(param);
        if (pd != null) {
            this.returnJson(ResultVo.success(pd.convert(GoodsConverter.convert(pd.getPageData()))));

        } else {

            this.returnJson(ResultVo.success(new PageData<>(param.getPageNo(), param.getPageSize(), 0, new ArrayList<Goods>())));
        }
    }

    /**
     * 查询商铺的商品分类与商品
     */
    @Before(CommonValidator.ShopIdValidator.class)
    public void findShopCategoriesGoodses() {
        int userId = UB.i(getPara("userId"));
        int shopId = getParaToInt("shopId", -1);

        List<GoodsCategory> goodsCategories = categoryService.findByShopId(shopId);
        List<GoodsCategoryVo> categories = GoodsCategoryConverter.convert(goodsCategories);

        List<Goods> goodses = goodsService.findByShopId(shopId);
        List<GoodsVo> goodsVos = GoodsConverter.convert(goodses);

        Map<Integer, List<GoodsVo>> goodsMap = new LinkedHashMap<>();
        if (goodsVos != null && goodsVos.size() > 0) {
            for (GoodsVo vo : goodsVos) {
                if (goodsMap.containsKey(vo.getSgCatId())) {
                    goodsMap.get(vo.getSgCatId()).add(vo);
                } else {
                    goodsMap.put(vo.getSgCatId(), Colls.toArrayList(vo));
                }
            }
        }
        if (categories != null && categories.size() > 0) {
            for (GoodsCategoryVo vo : categories) {
                if (goodsMap.containsKey(vo.getCategoryId())) {
                    vo.setGoodses(goodsMap.get(vo.getCategoryId()));
                }
            }
        }

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("categories", categories);

        this.returnJson(ResultVo.success(dataMap));
    }

    public void findMarketCategoryGoodses() {
        int userId = UB.i(getPara("userId"));
        int marketId = getParaToInt("marketId", -1);
        int categoryId = getParaToInt("categoryId", -1);

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(ParamNames.marketId, marketId);
        queryMap.put(ParamNames.categoryId, categoryId);
        PageParam<Map<String, Object>> param = toPageParam(queryMap);

        PageData<Goods> pd = goodsService.pageFind(param);
        if (pd == null || Colls.isEmpty(pd.getPageData())) {
            this.returnJson(ResultVo.success(pd));

        } else {
            List<GoodsVo> goodsVos = GoodsConverter.convert(pd.getPageData());
            this.returnJson(ResultVo.success(pd.convert(goodsVos)));
        }
    }

    // 查询商品详情
    public void detail() {
        int userId = UB.i(getPara("userId"));

        // 查询数据
        int goodsId = UB.i(getPara("goodsId"));
        Goods goods = goodsService.findByGoodsId(goodsId);

        // 转换数据
        GoodsVo vo = GoodsConverter.convert(goods);

        this.setShopInfo(vo);

        this.setMediaSources(Arrays.asList(vo));

        // 返回数据
        this.returnJson(ResultVo.success(vo));
    }

    private void setShopInfo(GoodsVo vo) {
        Shop shop = shopService.findById(vo.getShopId());
        vo.setShopName(shop.getName());
        vo.setShopLogo(shop.getStr(Shop.logo));
        vo.setShopSummary(shop.getStr(Shop.summary));
    }

    public void recommend() {
        int userId = UB.i(getPara("userId"));
        int bizId = UB.i(getPara("bizId"));
        String recommendType = getPara("type");

        List<Goods> goodses = goodsService.findRecommends(bizId, Goods.RecommendType.valueOf(recommendType));

        List<GoodsVo> goodsVos = GoodsConverter.convert(goodses);

        // 返回数据
        this.returnJson(ResultVo.success(goodsVos));
    }

    private void setMediaSources(List<GoodsVo> vos) {
        List<Integer> bizIds = new ArrayList<>();
        for (GoodsVo vo : vos) {
            bizIds.add(vo.getId());
        }

        Map<String, List<MediaSource>> mediaSourceMap = mediaSourceService.find(MediaSource.BizType.GOODS, bizIds);
        if (mediaSourceMap == null) {
            return;
        }

        for (GoodsVo vo : vos) {
            String key = MediaSource.BizType.GOODS.name() + vo.getId();
            List<MediaSource> mediaSources = mediaSourceMap.get(key);

            List<MediaSourceVo> mediaSourceVos = MediaSourceConverter.convert(mediaSources);
            vo.setMediaSources(mediaSourceVos);
        }
    }
}
